<template>
  <div class="dialog">
    <el-dialog :title="'防治记录' + titleText" :visible.sync="showDialog" width="55%" top="0" :close-on-click-modal="false"
      @close="cancel">
      <el-form ref="ruleForm" label-position="left" :model="formData" :rules="rules" class="el-form">

        <el-form-item label="预防/防治:" prop="type" class="w50p">
          <el-select filterable clearable v-model="formData.type" placeholder="请选择" :disabled="nowChanceStau === 'edit'">
            <el-option v-for="(item, index) in EpidemicPreventionType" :label="item.value" :value="item.name"
              :key="index + 'EpidemicPreventionType'" />
          </el-select>
        </el-form-item>

        <el-form-item label="防治疫病名称:" prop="diseaseBankId" class="w50p" v-if="formData.type == 'EpidemicPrevention'">
          <el-select filterable clearable v-model="formData.diseaseBankId" placeholder="请选择疫病">
            <el-option v-for="(item, index) in diseaseBankList" :label="item.diseaseName" :value="item.diseaseBankId"
              :key="index + 'diseaseBank'" />
          </el-select>
        </el-form-item>
        <el-form-item label="鱼塘名称:" prop="fishPondId" class="w50p">
          <!-- <el-select filterable clearable v-model="formData.fishPondId" placeholder="请选择鱼塘" filterable clearable @change="getFishPond"> -->
          <el-select filterable clearable v-model="formData.fishPondId" placeholder="请选择鱼塘">
            <el-option v-for="(item, index) in pondList" :label="item.pondName" :value="item.fishPondId"
              :key="index + 'diseaseBank'" />
          </el-select>
        </el-form-item>
        <el-form-item label="药品名称 ：" class="w100p">
          <div class="line-click" @click="addMaterial()">
            <i class="el-icon-plus"></i>
          </div>
          <div class="hang-content">
            <div v-for="(key, index) in formData.epidemicPreventionDetailList" :key="index + 'deviceCode'"
              class="hang-content-one">
              <el-form-item :prop="'epidemicPreventionDetailList.' + index + '.materialId'" class="w100p"
                :rules="{ required: true, message: '药品名称不能为空', trigger: ['change', 'blur'] }">
                <el-select filterable clearable v-model="key.materialId">
                  <el-option v-for="item of materialAllList" :key="item.materialId + 'materialId'" :label="item.name"
                    :value="item.materialId" />
                </el-select>
              </el-form-item>

              <el-form-item :prop="'epidemicPreventionDetailList.' + index + '.num'" class="w100p"
                :rules="{ required: true, emptyMsg: '用药数量不能为空', trigger: 'blur', validator: checkInt }">
                <el-input v-model="key.num" type="number" clearable placeholder="请输入用药数量" @change="() => {
                  key.epidemicNum = key.num / materialObj[key.materialId].ratioNum
                  $set(key, index, {
                    ...key, ...{
                      epidemicNum: key.epidemicNum,
                      num: key.num
                    }
                  })
                }">
                  <i slot="suffix" class="el-input__icon">{{ key.materialId ? materialObj[key.materialId].unit : '' }}</i>
                </el-input>
              </el-form-item>

              <el-form-item :prop="'epidemicPreventionDetailList.' + index + '.epidemicNum'" class="w100p"
                :rules="{ required: true, emptyMsg: '数量不能为空', trigger: 'blur', validator: checkInt }">
                <el-input v-model="key.epidemicNum" type="number" clearable placeholder="请输入数量" @change="() => {
                  key.num = key.epidemicNum * materialObj[key.materialId].ratioNum
                  $set(key, index, {
                    ...key, ...{
                      epidemicNum: key.epidemicNum,
                      num: key.num
                    }
                  })
                }">
                  <i slot="suffix" class="el-input__icon">{{ key.materialId ? materialObj[key.materialId].aUnit : ''
                  }}</i>
                </el-input>
              </el-form-item>

              <div class="line-click" @click="delMaterial(index)">
                <i class="el-icon-minus"></i>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="操作人:" class="w50p" prop="staffName">
          <el-select filterable clearable disabled v-model="formData.staffId" allow-create @change="staffChange">
            <el-option v-for="item of staffList" :key="item.staffId + 'staff'" :label="item.staffName"
              :value="item.staffId" />
          </el-select>
        </el-form-item>

        <el-form-item label="操作日期:" class="w50p" prop="operationTime">
          <el-date-picker v-model="formData.operationTime" type="datetime" placeholder="选择日期"
            value-format="yyyy-MM-dd HH:mm:ss" clearable />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="cancelbtn" @click="cancel()">取 消</el-button>
        <el-button type="primary" class="savebtn" @click="save('ruleForm')">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import EpidemicPreventionManagementApi from "@/api/health-management/epidemic-prevention-management";
import DiseaseBankApi from "@/api/basic-info-manage/diseaseBank";
import MaterialApi from "@/api/basic-info-manage/material";
import FishPondApi from "@/api/basic-info-manage/fishPond";
import { dialogMixin } from "@/utils/dialogMixin"
import EnumApi from "@/api/enum";
import store from "@/store";
export default {
  name: '',
  components: {},
  mixins: [dialogMixin],
  props: {
    // 弹框名称
    titleText: {
      type: String,
      default: ""
    },
    nowChanceStau: {
      type: String,
      default: ""
    },
    show: {
      type: Boolean,
      default: false
    },
    editObject: {
      type: [Object],
      default: () => {
        return {}
      }
    },
    materialList: {
      type: [Array],
      default: () => {
        return []
      }
    },
    staffList: {
      type: [Array],
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      formData: {
        staffName: '',
        staffId: '',
        epidemicPreventionDetailList: [{
          materialId: '',
          num: ''
        }]
      },
      rules: {
        type: [
          { required: true, message: "请选择消杀/防治类型", trigger: ["change", "blur"] }
        ],
        fishPondId: [
          { required: true, message: "请选择鱼塘", trigger: ["change", "blur"] }
        ],
        staffId: [
          { required: true, message: "请输入员工名称", trigger: ["change", "blur"] }
        ],
        diseaseBankId: [
          { required: true, message: "请选择疫病", trigger: ["change", "blur"] }
        ],
        operationTime: [
          { required: true, message: "请选择操作时间", trigger: ["change", "blur"] }
        ],
      },
      diseaseBankList: [],
      materialAllList: [],
      pondList: [],
      EpidemicPreventionType: [],
      showDialog: this.show
    };
  },
  computed: {
    materialObj() {
      return store.state.basicData.material;
    }
  },
  watch: {
    show(v) {
      this.showDialog = v;
      if (v) {
        this.queryDiseaseBank()
        this.queryPond()
        this.queryMaterial()
        this.queryEnum()
      }
    },
    nowChanceStau(v) {
      if (v === 'add') {
        this.formData = {
          staffName: '',
          staffId: '',
          epidemicPreventionDetailList: [{
            materialId: '',
            num: ''
          }]
        }
        let staffName = sessionStorage.getItem('staffName');
        let staffId = sessionStorage.getItem('staffId');
        let userList = this.staffList.filter(item => {
          return Number(item.staffId) === Number(staffId)
        })
        this.formData.staffName = userList.length == 0 ? this.staffList[0].staffName : staffName
        this.formData.staffId = userList.length == 0 ? this.staffList[0].staffId : Number(staffId)
        this.$set(this.formData, 'operationTime', this.getNowTime())
        this.formData.epidemicPreventionDetailList = [{
          materialId: '',
          num: '',
          epidemicNum: ''
        }]
        this.$nextTick(() => {
          this.$refs['ruleForm'].clearValidate()
        })
      }
      if (v === 'edit') {
        this.formData = this.editObject
        this.formData.epidemicPreventionDetailList.forEach((key, index) => {
          this.$set(this.formData.epidemicPreventionDetailList, index, {
            ...key, ...{
              epidemicNum: key.num / this.materialObj[key.materialId].ratioNum
            }
          })
        })
      }
    }
  },
  methods: {
    // getFishPond (e) {
    //   this.pondList.find(item => {
    //     if (item.fishPondId === e) {
    //       this.buildDateTime = new Date(item.buildDateTime)
    //       maxTime = new Date(this.buildDateTime)
    //       this.formData.uploadDateTime = this.formatDateTimeMHS(maxTime)
    //       console.log(maxTime)
    //     }
    //   })
    // },
    checkInt(rule, value, callback) {
      if (value) {
        if (Number(value) && value > 0) {
          callback();
        } else {
          callback(new Error('请输入大于0数值'));
        }
      } else {
        callback(new Error(rule.emptyMsg));
      }
    },
    queryEnum() {
      EnumApi.list({ enumType: 'EpidemicPreventionType' }).then(res => {
        // this.EpidemicPreventionType = res.data
        this.EpidemicPreventionType = [
          {
            "name": "EpidemicPrevention",
            "value": "防治疾病"
          },
          {
            "name": "DisinfectWork",
            "value": "日常预防"
          }
        ]
      })
    },
    queryMaterial() {
      MaterialApi.queryByCondition({ materialTypeNo: 'drug' }).then(res => {
        this.materialAllList = res.data;
      })
    },
    queryPond() {
      FishPondApi.queryByCondition().then(res => {
        this.pondList = res.data
      })
    },
    queryDiseaseBank() {
      DiseaseBankApi.queryByCondition().then(res => {
        this.diseaseBankList = res.data
      })
    },

    staffChange(e) {
      this.staffList.find((item) => {
        if (item.staffId === e) {
          this.formData.staffName = item.staffName
          return true
        }
      })
    },

    // 点击添加按钮
    addMaterial() {
      this.formData.epidemicPreventionDetailList.push({
        materialId: '',
        num: ''
      })
      // this.$set(
      //   this.formData.epidemicPreventionDetailList,
      //   this.formData.epidemicPreventionDetailList.length,
      //   { materialId: '', num: '' }
      // );
    },
    // 删除改行
    delMaterial(index) {
      this.formData.epidemicPreventionDetailList.splice(index, 1);
    },

    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            EpidemicPreventionManagementApi.edit(this.formData).then(res => {
              if (res.success) {
                this.$message.success("修改成功！");
                this.close()
              } else {
                this.$message.error("系统错误,请稍后再试");
              }
            });
          } else if (this.nowChanceStau === "add") {
            EpidemicPreventionManagementApi.add(this.formData).then(res => {
              if (res.success) {
                this.$message.success("添加成功");
                this.close()
              } else if (res.success === false && res.errCode === 200) {
                this.$message.error(res.message);
              } else this.$message.error("系统错误,请稍后再试");
            });
          }
        } else {
          return false;
        }
      });
    },
    close() {
      this.$emit("closeDialog");
    },
    cancel() {
      this.$emit("cancelDialog");
    }
  }
};
</script>

<style lang="scss" scoped>
.line-click {
  min-width: 30px;
  height: 30px;
  // background-color: aqua;
  display: flex;
  justify-content: center;
  align-items: center;
  border: snow 1px solid;
  border-radius: 50%;
  margin-bottom: 10px;
  margin-top: 5px;
  margin-left: 5px;
  color: #fff;
  background-color: #003947;
  cursor: pointer;
}

.hang-content {
  width: 100%;

  .hang-content-one {
    width: 100%;
    display: flex;
    margin-bottom: 20px;
  }
}</style>
